package com.open.core;

import com.open.core.common.Configuration;
import com.open.core.handler.WebSocketHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class NettyServer {
    //ConcurrentHashMap是Java中线程安全的哈希表实现，适用于多线程并发访问的场景
    //存储所有用户
    public static final Map<String, Channel> USERS = new ConcurrentHashMap<>(1024);
    //所有用户（系统消息）
    public static final ChannelGroup GROUPALL = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    //群发消息
    public static final ChannelGroup GROUP = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public static void start() throws Exception {

        EventLoopGroup boos = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            //创建服务端的启动对象，设置参数
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boos, worker)
                    //设置服务端通道实现类型
                    .channel(NioServerSocketChannel.class)
                    //使用匿名内部类的形式初始化通道对象
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {

                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //因为基于http协议，使用http的编码和解码器
                            pipeline.addLast(new HttpServerCodec())
                                    //是以块方式写,添加ChunkedwriteHandler处理器,用于支持异步写大数据流,将数据分成小块。
                                    .addLast(new ChunkedWriteHandler())
                                    //http数据在传输过程中是分段，HttpobjectAggregator,将多个段聚合
                                    .addLast(new HttpObjectAggregator(1024 * 64))
                                    /* 1.WebSocketServerProtocolHandler 核心功能是将http协议升级为ws协议，保持长连接
                                    2."/" 表示websocket请求地址的根路径 */
                                    .addLast(new WebSocketServerProtocolHandler("/"))
                                    //处理io
                                    .addLast(new WebSocketHandler());
                        }
                    });


            ChannelFuture future = bootstrap.bind(Configuration.NETTY_PORT).sync();
            System.out.println("服务器启动成功," + Configuration.NETTY_HOST + ":" + Configuration.NETTY_PORT);
            future.channel().closeFuture().sync();
        } finally {
            boos.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        NettyServer.start();
    }
}
